package com.aids_malaria.ui.setting;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.InputType;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.adapter.WorkAreaManagerAdapter;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.event.Events;
import com.aids_malaria.helper.PointLengthFilter;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.AreaC;
import com.aids_malaria.http.response.AreaV;
import com.aids_malaria.http.response.WorkAreaResponse;
import com.aids_malaria.ui.datacollect.CountySelectActivity;
import com.aids_malaria.util.AppUtil;
import com.aids_malaria.util.AuthUtil;
import com.aids_malaria.util.DeviceIdManager;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.SpUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.titlebar.TitleBar;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class WorkAreaSettingActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_county)
    TextView et_county;
    @BindView(R.id.et_x1)
    EditText et_x1;
    @BindView(R.id.et_y1)
    EditText et_y1;
    @BindView(R.id.et_x2)
    EditText et_x2;
    @BindView(R.id.et_y2)
    EditText et_y2;
    @BindView(R.id.cb_check_all)
    CheckBox cb_check_all;
    @BindView(R.id.rg_work_model)
    RadioGroup rg_work_model;
    @BindView(R.id.rb_online)
    RadioButton rb_online;
    @BindView(R.id.rb_offline)
    RadioButton rb_offline;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    private List<WorkAreaResponse.VillageDataBean> mData = new ArrayList<>();
    private WorkAreaManagerAdapter workAreaManagerAdapter;
    private String countyCode = "";
    private String countyName = "";
    private WorkAreaResponse mWorkAreaResponse;
    private boolean isWorkModelOnLine = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_work_area_setting;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitleBar(title_bar, ResourceUtil.getString(R.string.setting_work_area));

        PointLengthFilter pointLengthFilter = new PointLengthFilter(6);
        et_x1.setFilters(new InputFilter[]{pointLengthFilter});
        et_x2.setFilters(new InputFilter[]{pointLengthFilter});
        et_y1.setFilters(new InputFilter[]{pointLengthFilter});
        et_y2.setFilters(new InputFilter[]{pointLengthFilter});
        et_x1.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        et_x2.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        et_y1.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        et_y2.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);

        initRefreshLayout();
        //获取工作模式状态
        isWorkModelOnLine = SpUtil.getBoolean(mContext, Constant.IS_WORK_MODEL_ON_LINE,true);
        if(isWorkModelOnLine){
            rb_online.setChecked(true);
            rb_offline.setChecked(false);
        }else{
            rb_online.setChecked(false);
            rb_offline.setChecked(true);
        }
        cb_check_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = cb_check_all.isChecked();
                for (int i=0; i<mData.size(); i++){
                    mData.get(i).setCheck(checked);
                    workAreaManagerAdapter.notifyDataSetChanged();
                }
            }
        });

        rg_work_model.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.rb_online:
                        isWorkModelOnLine = true;
                        SpUtil.putBoolean(mContext, Constant.IS_WORK_MODEL_ON_LINE,isWorkModelOnLine);
                        break;
                    case R.id.rb_offline:
                        isWorkModelOnLine = false;
                        SpUtil.putBoolean(mContext, Constant.IS_WORK_MODEL_ON_LINE,isWorkModelOnLine);
                        ToastUtil.showToast(ResourceUtil.getString(R.string.please_set_work_area_and_download_data));
                        break;
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        initRecycleView();
        getWorkArea();
    }

    private void initRefreshLayout() {
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishLoadMore(1500);
                getWorkArea();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishRefresh(1000);
                getWorkArea();
            }
        });
    }

    private void initRecycleView() {
        refresh_layout.setEnableLoadMore(false);
        rv_data.setLayoutManager(new LinearLayoutManager(mContext));
        workAreaManagerAdapter = new WorkAreaManagerAdapter(mContext,R.layout.item_work_area_manager,mData);
        rv_data.setAdapter(workAreaManagerAdapter);
        workAreaManagerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                int totalselect = 0;
                for (int i=0; i<mData.size(); i++) {
                    if(position == i){
                        mData.get(i).setCheck(!mData.get(i).isCheck());
                    }else{
                        //mData.get(i).setCheck(false);
                    }
                    if(mData.get(i).isCheck()){
                        totalselect++;
                    }
                }
                if (totalselect < mData.size() ){
                    cb_check_all.setChecked(false);
                }
                workAreaManagerAdapter.notifyDataSetChanged();
            }
        });
    }

    @OnClick({R.id.iv_select,R.id.tv_gain,R.id.tv_confirm,R.id.et_county})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_select:
            case R.id.et_county:
                startActivity(CountySelectActivity.class);
                break;
            case R.id.tv_gain:
//                getLocation();
                String xFr = et_x1.getText().toString().trim();
                String yFr = et_y1.getText().toString().trim();
                String xTo = et_x2.getText().toString().trim();
                String yTo = et_y2.getText().toString().trim();
                if(StringUtil.isEmpty(xFr) || StringUtil.isEmpty(yFr) || StringUtil.isEmpty(xTo) || StringUtil.isEmpty(yTo)){
                    ToastUtil.showToast(ResourceUtil.getString(R.string.coordinate_can_not_be_empty));
                    return;
                }
                getGPSRangeVillage(xFr,yFr,xTo,yTo);
                break;
            case R.id.tv_confirm:
                //有未上传数据，请先上传再更改

                if(null == mWorkAreaResponse){
                    mWorkAreaResponse = new WorkAreaResponse();
                }
                if(!StringUtil.isEmpty(countyCode)){
                    mWorkAreaResponse.setCounty_code(countyCode);
                }
                if(!StringUtil.isEmpty(countyName)){
                    mWorkAreaResponse.setCounty_name(countyName);
                }
                List<WorkAreaResponse.VillageDataBean> villageDataBeanList = new ArrayList<>();
                for (int i=0; i<mData.size(); i++){
                    if(mData.get(i).isCheck()){
                        villageDataBeanList.add(mData.get(i));
                    }
                }
                //如果没有county_code，默认选择村的第一条县代码
                if(StringUtil.isEmpty(mWorkAreaResponse.getCounty_code())){
                    if(villageDataBeanList.size()>0){
                        mWorkAreaResponse.setCounty_code(villageDataBeanList.get(0).getCounty_code());
                    }
                }
                mWorkAreaResponse.setVillage_data(villageDataBeanList);
                mWorkAreaResponse.setPad_id(AppUtil.getDeviceId(mContext));
                if(isOnLine()){
                    List<WorkAreaResponse> workAreaResponseList = new ArrayList<>();
                    workAreaResponseList.add(mWorkAreaResponse);
                    String dataJson = GsonUtil.beanToJson(workAreaResponseList);
                    LogUtil.d("dataJson:------------" + dataJson);
                    saveWorkarea(mWorkAreaResponse.getBusy_type(), dataJson);
                }else{
                    List<WorkAreaResponse> workAreaResponseList = DBManager.get().workAreaResponseDao().getAll();
                    if(workAreaResponseList.size()>0){
                        WorkAreaResponse workAreaResponse = workAreaResponseList.get(0);
                        if(!isListEquals(workAreaResponse.getVillage_data(),mWorkAreaResponse.getVillage_data())){
                            //不相同，清除数据
                            clearUploadDownloadData();
                        }
                    }

                    DBManager.get().workAreaResponseDao().insert(mWorkAreaResponse);
                    ToastUtil.showToast(getString(R.string.operate_success));
                    finish();
                }
                break;
        }
    }

    /**
     * 获取工作区域设置数据
     *
     */
    private void getWorkArea() {
        if (!AuthUtil.isHaveQueryAuthByCode(Constant.SETTING_WORK_AREA)){
            return;
        }
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getWorkArea()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<WorkAreaResponse>>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(List<WorkAreaResponse> data) throws Exception {
                        if(data.size()>0){
                            mWorkAreaResponse = data.get(0);
                            mWorkAreaResponse.setBusy_type("2");
                            et_x1.setText(data.get(0).getX1());
                            et_y1.setText(data.get(0).getY1());
                            et_x2.setText(data.get(0).getX2());
                            et_y2.setText(data.get(0).getY2());
                            mData.clear();
                            mData.addAll(data.get(0).getVillage_data());
                            int totalSelect = 0;
                            for (int i = 0; i < mData.size(); i++) {
                                if (mData.get(i).isCheck()){
                                    cb_check_all.setChecked(true);
                                }
                            }
                            workAreaManagerAdapter.notifyDataSetChanged();
                        }else{
                            mWorkAreaResponse = new WorkAreaResponse();
                            mWorkAreaResponse.setBusy_type("1");
                            mWorkAreaResponse.setCreating_time("");
                            mWorkAreaResponse.setCounty_code("");
                            mWorkAreaResponse.setCounty_name("");
                            mWorkAreaResponse.setX1("0");
                            mWorkAreaResponse.setY1("0");
                            mWorkAreaResponse.setX2("0");
                            mWorkAreaResponse.setY2("0");
                            mWorkAreaResponse.setCreator("");
                            mWorkAreaResponse.setWork_mode(isWorkModelOnLine?"1":"0");
                            mWorkAreaResponse.setPad_id(AppUtil.getDeviceId(mContext));
                            mWorkAreaResponse.setVillage_data(new ArrayList<>());
                        }

                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    /**
     * 保存工作区域设置数据
     * @param busy_type 保存类型 1插入 2更改 3 删除
     * @param data {"pad_id":"110001","village_data":[{"village_code":"150001","village_name":"Conde",
     *             "xy":"x:1.0,y:1.0"},{"village_code":"150003","village_name":"Micoló","xy":"x:1.0,y:1.0"}],
     *             "work_mode":1,"x1":1,"x2":2,"y1":1,"y2":2}
     * @return
     */
    private void saveWorkarea(String busy_type, String data) {
        if (!AuthUtil.isHaveUpdateAuthByCode(Constant.SETTING_WORK_AREA)){
            ToastUtil.showNoPermission();
            return;
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data);
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).saveWorkarea(busy_type, requestBody)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<Object>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(Object data) throws Exception {
                        ToastUtil.showToast(getString(R.string.operate_success));
                        mWorkAreaResponse.setBusy_type("2");

                        List<WorkAreaResponse> workAreaResponseList = DBManager.get().workAreaResponseDao().getAll();
                        if(workAreaResponseList.size()>0){
                            WorkAreaResponse workAreaResponse = workAreaResponseList.get(0);
                            if(!isListEquals(workAreaResponse.getVillage_data(),mWorkAreaResponse.getVillage_data())){
                                //不相同，清除数据
                                clearUploadDownloadData();
                            }
                        }

                        DBManager.get().workAreaResponseDao().deleteAll();
                        DBManager.get().workAreaResponseDao().insert(mWorkAreaResponse);//更新本地工作区域
                        finish();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }


    /**
     * 获取行政村数据
     *
     */
    private void getVillage() {
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getVillage(countyCode,"")
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<AreaV>>() {

                    @Override
                    protected void onStart() {

                    }

                    @Override
                    protected void onSuccess(List<AreaV> data) throws Exception {
                        List<WorkAreaResponse.VillageDataBean> villageDataBeanList = new ArrayList<>();
                        for (int i=0; i<data.size(); i++){
                            AreaV areaV = data.get(i);
                            WorkAreaResponse.VillageDataBean villageDataBean = new WorkAreaResponse.VillageDataBean();
                            villageDataBean.setCounty_code(areaV.getCounty_code());
                            villageDataBean.setVillage_code(areaV.getVillage_code());
                            villageDataBean.setVillage_name(areaV.getVillage_name());
                            villageDataBean.setXy("x:" + areaV.getX() + ",y:" + areaV.getY());
                            villageDataBeanList.add(villageDataBean);
                        }
                        mData.clear();
                        cb_check_all.setChecked(false);
                        mData.addAll(villageDataBeanList);
                        workAreaManagerAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFinish() {

                    }
                });
    }

    /**
     * 获取GPS范围内的行政村数据
     *
     */
    private void getGPSRangeVillage(String xFr, String yFr, String xTo, String yTo) {
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getGPSRangeVillage(xFr, yFr, xTo, yTo)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<AreaV>>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(List<AreaV> data) throws Exception {
                        List<WorkAreaResponse.VillageDataBean> villageDataBeanList = new ArrayList<>();
                        for (int i=0; i<data.size(); i++){
                            AreaV areaV = data.get(i);
                            WorkAreaResponse.VillageDataBean villageDataBean = new WorkAreaResponse.VillageDataBean();
                            villageDataBean.setCounty_code(areaV.getCounty_code());
                            villageDataBean.setVillage_code(areaV.getVillage_code());
                            villageDataBean.setVillage_name(areaV.getVillage_name());
                            villageDataBean.setXy("x:" + areaV.getX() + ",y:" + areaV.getY());
                            villageDataBeanList.add(villageDataBean);
                        }
                        mData.clear();
                        mData.addAll(villageDataBeanList);
                        workAreaManagerAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    /**
     * 县选择回调
     * @param countySelectEvent
     */
    @Subscribe
    public void onCodeEvent(Events.CountySelectEvent countySelectEvent){
        AreaC areaC = countySelectEvent.getAreaC();
        et_county.setText(areaC.getCounty_name());
        countyCode = areaC.getCounty_code();
        countyName = areaC.getCounty_name();
        et_x1.setText("");
        et_y1.setText("");
        et_x2.setText("");
        et_y2.setText("");
        getVillage();
    }

    /**
     * 修改工作区域时候清空上传下载本地数据
     */
    private void clearUploadDownloadData(){
        SpUtil.putInt(mContext, Constant.DOWNLOADED_SETTING_COUNT,0);
        SpUtil.putInt(mContext, Constant.DOWNLOADED_ADMINISTRATIVE_VILLAGE_COUNT,0);
        SpUtil.putInt(mContext, Constant.DOWNLOADED_PERSONNEL_DATA_COUNT,0);

        DBManager.get().userDao().deleteAll();
        DBManager.get().roleAuthDao().deleteAll();
        DBManager.get().workAreaResponseDao().deleteAll();

        DBManager.get().areaCDao().deleteAll();
        DBManager.get().areaVDao().deleteAll();
        DBManager.get().mosquitoInvestDao().deleteAll();

        DBManager.get().padMaxIdentitySeqDao().deleteAll();
        DBManager.get().workAreaPersonIDDao().deleteAll();
        DBManager.get().personDataDao().deleteAll();
        DBManager.get().diagnosisInfoPackDao().deleteAll();
        DBManager.get().eaProcessPackDao().deleteAll();
        DBManager.get().getMedicalTreatmentPackDao().deleteAll();
        DBManager.get().drugallergyInfoPackDao().deleteAll();
        DBManager.get().premedicalTreatmentPackDao().deleteAll();

        SpUtil.putInt(mContext, Constant.UPLOAD_PERSON_DATA_COUNT,0);
        SpUtil.putInt(mContext, Constant.UPLOAD_ADMINISTRATIVE_VILLAGE_COUNT,0);

    }

    /**
     * 比较两个集合是否相等
     * @param aList
     * @param bList
     * @return
     */
    public static boolean isListEquals(List<WorkAreaResponse.VillageDataBean> aList, List<WorkAreaResponse.VillageDataBean> bList) {
        if (aList.size() != bList.size()){
            return false;
        }
        int n = aList.size();
        int i = 0;
        while (n-- != 0) {
            if (!aList.get(i).getVillage_code().equals(bList.get(i).getVillage_code()))
                return false;
            i++;
        }
        return true;
    }

}
